﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AutoUpdate.register;

namespace AutoUpdate
{
    public class Program
    {
        static int downloadPercntage = 0;
        const string VERSION_REG_KEY = "version";
        const string DETAIL_REG_KEY = "detail";
        const string REG_PATH = "SOFTWARE\\AngleExpress\\";
        static FileUpdater fileUpdater = new FileUpdater();
        static Register register = new Register(REG_PATH, RegDomain.CurrentUser);

        static void Main(string[] args)
        {
            try
            {
                fileUpdater.killProcess();

                Console.WriteLine("开始检查最新版本号");
                var versionTask = fileUpdater.getLatestVersion();

                while (!versionTask.IsCompleted)
                    continue;
                if (versionTask.IsFaulted)
                {
                    Console.WriteLine(versionTask.Exception.InnerException.Message);
                    Console.ReadLine();
                    return;
                }

                FileUpdater.Version remoteVer = versionTask.Result;
                Console.WriteLine("最新版本号：" + remoteVer.number);

                Console.WriteLine("开始下载更新包");
                Task<string> downloadTask = fileUpdater.download(remoteVer.url, progressHandler);
                downloadTask.Wait();
                string zipPath = downloadTask.Result;
                //Console.WriteLine("下载完毕：" + zipPath);
                Console.WriteLine("下载文件完毕");

                string zipDir = fileUpdater.unzip(zipPath);
                //Console.WriteLine("解压完成：" + zipDir);
                Console.WriteLine("解压完毕");

                fileUpdater.replaceFiles(zipDir, AppDomain.CurrentDomain.BaseDirectory);
                Console.WriteLine("文件更新完毕");

                register.WriteRegeditKey(VERSION_REG_KEY, remoteVer.number);
                register.WriteRegeditKey(DETAIL_REG_KEY, remoteVer.title);
                Console.WriteLine("升级结束，回车键关闭程序，Bye");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }

        static void progressHandler(object sender, DownloadProgressChangedEventArgs e)
        {
            if (downloadPercntage == e.ProgressPercentage)
                return;
            downloadPercntage = e.ProgressPercentage;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < e.ProgressPercentage; i++)
                sb.Append("#");
            Console.WriteLine(sb.ToString() + "%" + e.ProgressPercentage);
        }

        public string localVersion()
        {
            object ret = register.ReadRegeditKey(VERSION_REG_KEY);
            if (ret == null)
            {
                Console.WriteLine("本地版本号格式异常");
                return "未知";
            }
            return ret.ToString();
        }

        public async Task<bool> hasNewVersion()
        {
            FileUpdater.Version ver = await fileUpdater.getLatestVersion();
            return !localVersion().Equals(ver.number);
        }

        public string getGoogleVer()
        {
            return getSupportBrowserVer("google");
        }

        public string getFireFoxVer()
        {
            return getSupportBrowserVer("firefox");
        }

        public string get360Ver()
        {
            return getSupportBrowserVer("360");
        }

        public string getEdgeVer()
        {
            return getSupportBrowserVer("edge");
        }

        private string getSupportBrowserVer(string browser)
        {
            object ret = register.ReadRegeditKey(DETAIL_REG_KEY);
            if (ret == null)
            {
                return "未知";
            }
            var browserVers = ret.ToString().Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string browserVer in browserVers)
            {
                var array = browserVer.Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries);
                if (array.Length == 2 && array[0] == browser)
                {
                    return array[1];
                }
            }
            return "未知";
        }
    }
}
